package hellfire.platform.input;

import hellfire.platform.screens.AbstractGameScreen;
import hellfire.system.graphics.GLDrawable;
import hellfire.system.graphics.GLImage;
import hellfire.system.graphics.GLVec2;
import android.util.Log;
import android.view.MotionEvent;

public class GLButton implements TouchListener, GLDrawable
{
	protected boolean down = false;
	private AbstractGameScreen screen;
	protected GLImage image;
	private Runnable event;
	private int pressed, notPressed;
	
	public GLButton(AbstractGameScreen screen, GLVec2 pos, GLVec2 dim, int imgNotpressed, int imgPressed, Runnable event)
	{
		this.screen = screen;
		image = new GLImage(imgNotpressed, pos, dim);
		this.event = event;
		this.pressed = imgPressed;
		this.notPressed = imgNotpressed;
	}
	
	public GLImage getImage()
	{
		return this.image;
	}
	
	public void setHandler(Runnable handler)
	{
		this.event = handler;
	}
	
	public void onTouchEvent(MotionEvent e, GLVec2 pos)
	{
		if(e.getAction() == MotionEvent.ACTION_DOWN)
		{
			screen.focusTouchListener(this);
			down = true;
			image.setImageResource(pressed);
		}
		else if(e.getAction() == MotionEvent.ACTION_UP)
		{
			if(down)
			{
				event.run();
				screen.focusTouchListener(null);
				image.setImageResource(notPressed);
			}
			down = false;
		}
		else if(e.getAction() == MotionEvent.ACTION_MOVE)
		{
			if(down)
			{
				if(!testPosition(pos))
				{
					//leave area
					down = false;
					image.setImageResource(notPressed);
					screen.focusTouchListener(null);
				}
			}
			
		}
	}
	
	@Override
	public void draw(float[] matrix) 
	{
		image.draw(matrix);
	}

	@Override
	public boolean testPosition(GLVec2 pos) 
	{
		return image.checkBounds(pos);
	}
	
	public GLVec2 getPos() 
	{
		return image.getPos();
	}
	
	public void setPos(GLVec2 pos) 
	{
		image.setPos(pos);
	}
}
